import pygst
pygst.require("0.10")
import gst
import pygtk
import gtk
import commands

class SendAudio:
	'''
	gst-launch-0.10 pulsesrc device="alsa_input.pci-0000_00_1b.0.analog-stereo" ! tcpclientsink host=localhost port=10000
	'''
	def __init__(self, address):
		self.pipeline = gst.Pipeline("audio_out")
		# Add audio source to pipeline
		self.pulsesrc = gst.element_factory_make("pulsesrc", "audio")
		devices = commands.getoutput('''pactl list | grep -A2 'Source #' | grep 'Name: ' | cut -d" " -f2''')
		print devices
		devices = devices.split('\n')
		#self.pulsesrc.set_property('device', 'alsa_input.pci-0000_00_1b.0.analog-stereo')
		self.pulsesrc.set_property('device', devices[1])
		self.pipeline.add(self.pulsesrc)
		print "Added audio source"
		# Add tcp connection
		self.tcpdest = gst.element_factory_make("tcpclientsink", 'tcpdest')
		self.tcpdest.set_property('host', address[0])
		self.tcpdest.set_property('port', address[1])
		self.pipeline.add(self.tcpdest)
		print "Added Network sink"
		# Link both stages
		self.pulsesrc.link(self.tcpdest)
		# Set the pipeline to play state
		self.pipeline.set_state(gst.STATE_PLAYING)
		# Store the play state for play/pause of audio
		self.playing = True
		print "Playing..."

	def start_stop(self):
		if self.playing == False:
			self.pipeline.set_state(gst.STATE_PLAYING)
			self.playing = True
		else:
			self.pipeline.set_state(gst.STATE_NULL)
			self.playing = False
#==============================================================================
class RecvAudio:
	'''
	gst-launch-0.10 tcpserversrc host=localhost port=10000 ! audio/x-raw-int, endianness="(int)1234", signed="(boolean)true", width="(int)16", depth="(int)16", rate="(int)44100", channels="(int)2" ! pulsesink
	'''
	def __init__(self, address):
		self.pipeline = gst.Pipeline("audio_in")
		# Add tcp source
		self.tcpsrc = gst.element_factory_make("tcpserversrc", 'tcpsrc')
		self.tcpsrc.set_property('host', address[0])
		self.tcpsrc.set_property('port', address[1])
		print "Added network source"
		# Add caps Filter
		self.caps = gst.Caps('audio/x-raw-int, endianness=(int)1234, signed=(boolean)true, width=(int)16, depth=(int)16, rate=(int)44100, channels=(int)2')
		self.filter = gst.element_factory_make("capsfilter", 'filter')
		self.filter.set_property('caps', self.caps)
		print "Added caps filters"
		# Add audio destination
		self.sink = gst.element_factory_make('pulsesink', "sink")
		print "Added audio sink"

		self.pipeline.add(self.tcpsrc, self.filter, self.sink)
		gst.element_link_many(self.tcpsrc, self.filter, self.sink)
		print "Receiving..."
		self.pipeline.set_state(gst.STATE_PLAYING)

